<?php

namespace backend\controllers;

use backend\models\JjrProject;
use backend\models\JjrUser;
use backend\models\JjrUserProject;
use backend\models\JjrUserWithdraw;
use Yii;
use backend\models\JjrUserCommission;
use yii\data\ActiveDataProvider;
use backend\controllers\BaseController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * JjrUserCommissionController implements the CRUD actions for JjrUserCommission model.
 */
class JjrUserCommissionController extends BaseController
{
    public $enableCsrfValidation = false;
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }


    /**
     * Lists all JjrUserCommission models.
     * @return mixed
     */
    public function actionIndex()
    {

        $query = JjrUserCommission::find()
            ->alias('uc')
            ->select("uc.*,p.name,u.real_name,up.client_real_name")
            ->leftJoin('yii2_jjr_user_project up','uc.jjr_user_project_id=up.id')
            ->leftJoin('yii2_jjr_project p','up.jjr_project_id=p.id')
            ->leftJoin('yii2_jjr_user u','up.jjr_user_id=u.id')
            ->asArray();
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single JjrUserCommission model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        $query = JjrUserCommission::find()
            ->alias('uc')
            ->select("uc.*,p.name,u.real_name,up.client_real_name")
            ->leftJoin('yii2_jjr_user_project up','uc.jjr_user_project_id=up.id')
            ->leftJoin('yii2_jjr_project p','up.jjr_project_id=p.id')
            ->leftJoin('yii2_jjr_user u','up.jjr_user_id=u.id')
            ->where(['uc.id'=>$id])
            ->asArray();
        $model = $query->one();
        //print_r($model);exit;
        return $this->render('view', [
            'model' =>$model,
        ]);
    }
    public function actionCreateSelf()
    {
        $model = new JjrUserCommission();
        if (Yii::$app->request->isPost&&$model->load(Yii::$app->request->post())) {
          //  print_r($_POST);exit;
            $userProjectId =$model->jjr_user_project_id;
            $userProject = JjrUserProject::findOne(['id'=>$userProjectId]);
            if(!$userProject){
               // $this->error('记录不存在');
                $model->addError('jjr_user_project_id','该项目不存在');
                return $this->render('create_self', [
                    'model' => $model
                ]);
            }
            $commission = JjrUserCommission::findOne(['jjr_user_project_id'=>$userProjectId]);
            if($commission){
                //$this->error('不能重复结佣');
                $model->addError('jjr_user_project_id','该项目不能重复结佣');
                return $this->render('create_self', [
                    'model' => $model
                ]);
            }
            $user = JjrUser::findOne(['id'=>$userProject->jjr_user_id]);
            if($user->identity ==JjrUser::IDENTITY_FREE&&$userProject->process<JjrUserProject::PROCESS_SIGN_UP){
                //$this->error('结佣条件不满足');
                $model->addError('jjr_user_project_id','该项目不满足结佣条件');
                return $this->render('create_self', [
                    'model' => $model
                ]);
            }else if($user->identity ==JjrUser::IDENTITY_COMPANY&&$userProject->process<JjrUserProject::PROCESS_PAY){
                //$this->error('结佣条件不满足');
                $model->addError('jjr_user_project_id','该项目不满足结佣条件');
                return $this->render('create_self', [
                    'model' => $model
                ]);
            }
            $model->jjr_user_id = $userProject->jjr_user_id;
            if($model->save()){
                return $this->redirect(['view', 'id' => $model->id]);
            }

    }
        $userProjectId = Yii::$app->request->get('userProjectId');
        $text="";
        if($userProjectId){
            $userProject = JjrUserProject::findOne(['id'=>$userProjectId]);
            $user = JjrUser::findOne(['id'=>$userProject->jjr_user_id]);
            $project = JjrProject::findOne($userProject->jjr_project_id);
            $model->jjr_user_project_id = $userProjectId;
            $text = "[{$project['name']}]经纪人:{$user['real_name']}客户:{$userProject['client_real_name']}";
        }



        return $this->render('create_self', [
            'model' => $model,
            'text'=>$text
        ]);
    }

    /**
     * Creates a new JjrUserCommission model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new JjrUserCommission();
        if (Yii::$app->request->isPost){

            //$this->error('操作错误--------------');
            $data = Yii::$app->request->post();
            $userProjectId =isset($data['jjr_user_project_id']) ?$data['jjr_user_project_id']: $data['JjrUserProject']['id'];
            $userProject = JjrUserProject::findOne(['id'=>$userProjectId]);
            if(!$userProject){
                $this->error('记录不存在');
            }
            $commission = JjrUserCommission::findOne(['jjr_user_project_id'=>$userProjectId]);
            if($commission){
                $this->error('不能重复结佣');
            }
            $user = JjrUser::findOne(['id'=>$userProject->jjr_user_id]);
            if($user->identity ==JjrUser::IDENTITY_FREE&&$userProject->process<JjrUserProject::PROCESS_SIGN_UP){
                $this->error('结佣条件不满足');
            }else if($user->identity ==JjrUser::IDENTITY_COMPANY&&$userProject->process<JjrUserProject::PROCESS_PAY){
                $this->error('结佣条件不满足');
            }
            $model->jjr_user_project_id = $userProjectId;
            $model->jjr_user_id = $userProject->jjr_user_id;
            $model->amount = $data['JjrUserCommission']['amount'];
            $model->transfer_status = $data['JjrUserCommission']['transfer_status'];

            if($model->save()){
                $this->success('添加成功');
            }else{
               $this->error('添加失败');
               exit;
            }

        }

        $userProjectId = Yii::$app->request->get('userProjectId');
        //经理人名字
        $userProject = JjrUserProject::findOne(['id'=>$userProjectId]);
        $user = JjrUser::findOne(['id'=>$userProject->jjr_user_id]);
        $project = JjrProject::findOne($userProject->jjr_project_id);

        return $this->render('create', [
            'model' => $model,'project'=>$project,'user'=>$user,'userProject'=>$userProject
        ]);
    }

    /**
     * Updates an existing JjrUserCommission model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            $model->amount = $data['JjrUserCommission']['amount'];
            $model->transfer_status = $data['JjrUserCommission']['transfer_status'];
            if($model->save()){
                return $this->redirect(['view', 'id' => $model->id]);
            }
        }
//        if ($model->load(Yii::$app->request->post()) && $model->save()) {
//            return $this->redirect(['view', 'id' => $model->id]);
//        }
        $userProjectId = $model->jjr_user_project_id;
        //经理人名字
        $userProject = JjrUserProject::findOne(['id'=>$userProjectId]);
        $user = JjrUser::findOne(['id'=>$userProject->jjr_user_id]);
        $project = JjrProject::findOne($userProject->jjr_project_id);
        return $this->render('update', [
            'model' => $model,'project'=>$project,'user'=>$user,'userProject'=>$userProject
        ]);
    }

    /**
     * Deletes an existing JjrUserCommission model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        $userWithdraw = JjrUserWithdraw::findOne(['jjr_user_commission_id'=>$model->id]);
        if($userWithdraw){
            $this->error("删除失败，已有提现数据");
        }else{
            $model->delete();
        }
        return $this->redirect(['index']);
    }

    /**
     * Finds the JjrUserCommission model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return JjrUserCommission the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = JjrUserCommission::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
